package com.lineage.server.command.executor;

import com.lineage.echo.ClientExecutor;
import com.lineage.list.OnlineUser;
import com.lineage.server.datatables.ItemTable;
import com.lineage.server.datatables.lock.AccountReading;
import com.lineage.server.datatables.lock.DwarfReading;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1Account;
import com.lineage.server.world.World;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class L1CN2 implements L1CommandExecutor {
  private static final Log _log = LogFactory.getLog(L1CN2.class);
  
  public static L1CommandExecutor getInstance() {
    return new L1CN2();
  }
  
  public void execute(L1PcInstance pc, String cmdName, String arg) {
    try {
      if (pc == null)
        _log.warn("这个命令只能在游戏中执行!"); 
      StringTokenizer st = new StringTokenizer(arg);
      String char_name = st.nextToken();
      String account_name = null;
      L1PcInstance target = World.get().getPlayer(char_name);
      if (target == null) {
        account_name = AccountReading.get().getPlayer(char_name);
      } else {
        account_name = target.getAccountName();
      } 
      L1Account acc = AccountReading.get().getAccount(account_name);
      if (acc != null) {
        int item_id = Integer.parseInt(st.nextToken());
        int count = 0;
        try {
          count = Integer.parseInt(st.nextToken());
        } catch (Exception e2) {
          count = 1;
        } 
        L1ItemInstance item = ItemTable.get().createItem(item_id);
        if (item != null) {
          item.setCount(count);
          pc.sendPackets((ServerBasePacket)new S_ServerMessage(166, "指定角色名(" + char_name + ")对应帐号(" + acc.get_login() + ")加入物品:" + 
                item.getName() + '(' + item_id + ") 数量" + count));
          DwarfReading.get().insertItem(acc.get_login(), item);
          ClientExecutor cl = OnlineUser.get().get(acc.get_login());
          if (cl != null) {
            L1PcInstance tgpc = cl.getActiveChar();
            if (tgpc != null)
              tgpc.getDwarfInventory().loadItems(); 
          } 
        } 
      } else {
        pc.sendPackets((ServerBasePacket)new S_ServerMessage(166, "指令异常: 角色名(" + char_name + ")没有找到对应的账号!!"));
      } 
    } catch (Exception e) {
      _log
        .error("错误的GM指令格式: " + getClass().getSimpleName() + " 执行的GM:" + pc.getName() + e.getMessage());
      pc.sendPackets((ServerBasePacket)new S_ServerMessage(261));
    } 
  }
}
